#!/usr/bin/env python
# -*- encoding: utf-8 -*-

import re
import requests as req
import json
import os
import time
from flask import Blueprint, render_template, request, jsonify, flash
from common.models.Kuaidi import Kuaidi
from application import db, app


route_kuaidi = Blueprint('kuaidi_page', __name__)
phoneorname = ""

re_words = re.compile(u"[\u4e00-\u9fa5]+")


def kd(no, ty="ems"):
    host = 'https://wuliu.market.alicloudapi.com/kdi'
    method = 'GET'
    appcode = app.config.get('KUAIDI_APPCODE')
    # 开通服务后 买家中心-查看AppCode
    querys = 'no={}&type={}'.format(no, ty)
    url = host + '?' + querys
    header = {"Authorization": 'APPCODE ' + appcode}
    try:
        res = req.get(url, headers=header)
    except:
        print("URL错误")
        exit()
    httpStatusCode = res.status_code

    if(httpStatusCode == 200):
        print("正常请求计费(其他均不计费)")
    else:
        httpReason = res.headers['X-Ca-Error-Message']
        if(httpStatusCode == 400 and httpReason == 'Invalid Param Location'):
            print("参数错误")
        elif(httpStatusCode == 400 and httpReason == 'Invalid AppCode'):
            print("AppCode错误")
        elif(httpStatusCode == 400 and httpReason == 'Invalid Url'):
            print("请求的 Method、Path 或者环境错误")
        elif(httpStatusCode == 403 and httpReason == 'Unauthorized'):
            print("服务未被授权（或URL和Path不正确）")
        elif(httpStatusCode == 403 and httpReason == 'Quota Exhausted'):
            print("套餐包次数用完")
        elif(httpStatusCode == 500):
            print("API网关错误")
        else:
            print("参数名错误 或 其他错误")
            print(httpStatusCode)
            print(httpReason)
    return (res.text)


@route_kuaidi.route("/")
def index():
    return render_template('kuaidi/kuaidi_index.html', title="快递查询", nume=1)


@route_kuaidi.route("/add", methods=['POST', 'GET'])
def add():
    if request.method == 'POST':
        a = request.values
        name = a['name'] if 'name' in a else ''
        phone = a['phone'] if 'phone' in a else ''
        no = a['no'] if 'no' in a else ''
        ty = a['ty'] if 'ty' in a else ''
        a = Kuaidi.query.filter_by(kuaidi_no=no).first()
        if name is None or len(name) < 1:
            flash('输入收件人名')
        elif phone is None or len(phone) < 1:
            flash('收件人手机号码还没有输入')
        elif no is None or len(no) < 1 or a:
            flash('快递单号已经存在！！！')
        elif ty is None or len(ty) < 1:
            flash('快递公司')
        else:
            b = Kuaidi(name=name, phone=phone,
                       kuaidi_no=no, kuaidi_ty=ty)
            db.session.add(b)
            db.session.commit()
            flash('添加成功')
    return render_template('kuaidi/kuaidi_add.html', title="快递输入", nume=1)


@route_kuaidi.route("/info", methods=['POST', 'GET'])
def info():
    global phoneorname
    if request.method == "GET":
        return render_template('kuaidi/kuaidi_info.html', title="快递查询")
    req = request.values
    phoneorname = req['phone'] if 'phone' in req else ''
    if phoneorname is None or len(phoneorname) < 1:
        keyword = 4
    if len(phoneorname) > 0:
        if re.match(re_words, phoneorname) is None:
            if len(phoneorname) == 11:
                keyword = 1
            else:
                keyword = 2
        else:
            keyword = 3
    b = chaxu(keyword)
    if type(b) == str:
        return render_template('kuaidi/kuaidi_info.html', title="快递查询", chaxu=b)
    else:
        return render_template('kuaidi/kuaidi_info.html', title="快递查询", kdtext=b)


def chaxu(keyword):
    '''
    数据库查询
    '''
    if keyword == 1:
        a = Kuaidi.query.filter_by(phone=phoneorname).first()
    elif keyword == 3:
        a = Kuaidi.query.filter_by(name=phoneorname).first()
    else:
        a = None
    if a is not None:
        if '已签收' in a.kdstatus:
            # 如果签收直接取数据库存放数据
            kdtext = a.kdstatus
        elif time.time() - float(a.kdcxshisj) < 21600000:
            # 查询时间相差少于6小时直接取数据库存放数据
            kdtext = a.kdstatus
            print('小于6小时')
        else:
            kdtext = kd(a.kuaidi_no)
            a.kdstatus = kdtext
            a.kdcxshisj = time.time()
            db.session.commit()
        kdtext = json.loads(kdtext)
        kdtext = kdtext['result']
        kdtext['sname'] = a.name
        kdtext['sphone'] = a.phone
    else:
        kdtext = "请输入收件人手机号玛、收件人姓名；或者您还没有购买，请扫描下方二维码 咨询购买，Let’s go"
    return kdtext
